package point

import (
	"sweetsunnyflower/app/models/user"

	"github.com/spf13/cast"
	"gorm.io/gorm"
)

// func (point *Point) BeforeSave(tx *gorm.DB) (err error) {}
// func (point *Point) BeforeCreate(tx *gorm.DB) (err error) {}
func (point *Point) AfterSave(tx *gorm.DB) (err error) {
	userModel := user.Get(cast.ToString(point.UserID))

	// 加积分
	if point.Action == AddAction {
		userModel.Point = userModel.Point + cast.ToUint64(point.Value)
	}

	// 减积分
	if point.Action == SubtractAction {
		if userModel.Point < cast.ToUint64(point.Value) {
			userModel.Point = 0
		} else {
			userModel.Point = userModel.Point - cast.ToUint64(point.Value)
		}
	}

	userModel.Save()

	return nil
}

// func (point *Point) BeforeUpdate(tx *gorm.DB) (err error) {}
// func (point *Point) AfterUpdate(tx *gorm.DB) (err error) {}
// func (point *Point) AfterSave(tx *gorm.DB) (err error) {}
// func (point *Point) BeforeDelete(tx *gorm.DB) (err error) {}
// func (point *Point) AfterDelete(tx *gorm.DB) (err error) {}
// func (point *Point) AfterFind(tx *gorm.DB) (err error) {}
